
do
    local co = coroutine.create(function()
        print("hello coroutined") 
        local r = coroutine.yield(5)
        print("hello coroutined again", "args:", r)
        return 15
    end)

    print("co:", co, ", type(co): ", type(co))
    print("coroutine.status(co):", coroutine.status(co))
    local r , v = coroutine.resume(co)
    print("coroutine.status(co):", coroutine.status(co), "r:", r, "v:", v)
    local r , v = coroutine.resume(co,  10)
    print("coroutine.status(co):", coroutine.status(co), "r:", r, "v:", v)
    
end

do
    print("\n ---------status-----------")
    local co1 = false
    local co2 = false

    co1 = coroutine.create(function ()
        print("co1,   co status:", coroutine.status(co2))
    end)
    co2 = coroutine.create(function ()
        print("co2,   co status:", coroutine.status(co2))
        coroutine.resume(co1)
        print("co2,   co status:", coroutine.status(co2))
    end)
    print("co1 status:", coroutine.status(co1))
    print("co2 status:", coroutine.status(co2))
    coroutine.resume(co2, co1)
    print("co1 status:", coroutine.status(co1))
    print("co2 status:", coroutine.status(co2))

end

do
    print("\n---coroutine.error---")
    local co = coroutine.create(function()
        error("error in coroutine")
    end)
    print("coroutine.status(co):", coroutine.status(co))
    local ok, err = coroutine.resume(co)
    print("coroutine.status(co):", coroutine.status(co))
    print("ok, err:", ok, err)
end

do
    print("\n---iterator---")
    local function hanoi(n, a, b, c)
        if n == 1 then
            coroutine.yield(a, c)
        else
            hanoi(n - 1, a, c, b)
            coroutine.yield(a, c)
            hanoi(n - 1, b, a, c)
        end
    end
    local function hanoiTower(n)
        local co = coroutine.create(function()
            hanoi(n, 'A', 'B', 'C')
        end)
        return function()
            local r, a, c = coroutine.resume(co)
            if r then
                return a, c
            end
        end
    end

    for a, c in hanoiTower(2) do
        print(a, '->', c)
    end

end

